package com.example.filemanager;


import com.example.filemanager.Bean.FileBean;
import com.google.gson.Gson;
import org.springframework.util.ResourceUtils;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import org.springframework.web.servlet.HandlerMapping;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.util.ArrayList;
import java.util.List;

@RestController
@RequestMapping("main")
public class mainApi {


    @RequestMapping(value = "fileUpload", method = {RequestMethod.GET, RequestMethod.POST})
    @ResponseBody
    public String fileUpload(@RequestParam("fileName") MultipartFile file
    ) {
        if (file.isEmpty()) {
            return "false";
        }
        String fileName = file.getOriginalFilename();
        int size = (int) file.getSize();
        System.out.println(fileName + "-->" + size);

        String path = ResPath.DownloadPath;
        File dest = new File(path + "/" + fileName);
        if (!dest.getParentFile().exists()) { //判断文件父目录是否存在
            dest.getParentFile().mkdir();
        }
        try {
            file.transferTo(dest); //保存文件
            return "true";
        } catch (IllegalStateException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
            return "false";
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
            return "false";
        }
    }


    @RequestMapping(value = "multifileUpload"
            , method = {RequestMethod.GET, RequestMethod.POST})
    public @ResponseBody
    String multifileUpload(HttpServletRequest request) {

        List<MultipartFile> files = ((MultipartHttpServletRequest) request).getFiles("fileName");

        if (files.isEmpty()) {
            return "false";
        }

        String path = ResPath.DownloadPath;

        for (MultipartFile file : files) {
            String fileName = file.getOriginalFilename();
            int size = (int) file.getSize();
            System.out.println(fileName + "-->" + size);

            if (file.isEmpty()) {
                return "false";
            } else {
                File dest = new File(path + "/" + fileName);
                if (!dest.getParentFile().exists()) { //判断文件父目录是否存在
                    dest.getParentFile().mkdir();
                }
                try {
                    file.transferTo(dest);
                } catch (Exception e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                    return "false";
                }
            }
        }
        return "true";
    }

    @RequestMapping(value = "/download/{name}"
            , method = {RequestMethod.GET, RequestMethod.POST})
    public void getDownload(@PathVariable String name
            , HttpServletRequest request, HttpServletResponse response)
            throws FileNotFoundException {
        System.out.println("Download fileName=" + name);
        Util.download(request, response, name);
    }


    @RequestMapping(value = "/get"
            , method = {RequestMethod.GET, RequestMethod.POST})
    public void Download(@RequestParam("name") String name
            , HttpServletRequest request, HttpServletResponse response)
            throws FileNotFoundException {
        if (name != null && !name.isEmpty()) {
            if (name.charAt(0) == '/' || name.charAt(0) == '\\') {
                name = name.substring(1);
            }
            System.out.println("Download fileName=" + name);
            Util.download(request, response, name);
        }
    }

    @GetMapping("/files/**/{filename:.+}")
    public void downloadFile(@PathVariable String filename, HttpServletRequest request, HttpServletResponse response) {
        String pathWithinApplication = (String) request.getAttribute(HandlerMapping.PATH_WITHIN_HANDLER_MAPPING_ATTRIBUTE);
        // 移除开头的"/files"和末尾的"/{filename}"部分
        String realPath = pathWithinApplication.replaceFirst("/main/files", "");
        if (!realPath.isEmpty()) {
            System.out.println("Download fileName=" + realPath);
            Util.download(request, response, realPath);
        }
    }


    @RequestMapping(value = "/index"
            , method = {RequestMethod.GET, RequestMethod.POST})
    public String getFilePath(@RequestParam(value = "path", required = false) String path) {
        File file;
        System.out.println("getFilePath  path=" + path);
        String pathName = "";
        file = new File(ResPath.DownloadPath);
        if (path != null && !path.isEmpty()) {
            file = new File(ResPath.DownloadPath + path);
            pathName = path.replace("/", "%2f");
        } else {
            path="";
        }

        StringBuilder stringBuilder = new StringBuilder();
        stringBuilder.append(ResPath.Html_Start);
        File[] tempList = file.listFiles();
        if (tempList == null) {
            return "没有文件";
        }
        for (int i = 0; i < tempList.length; i++) {
            if (tempList[i].isFile()) {
                stringBuilder.append("<p><a href=\"../main/files" + path + "/" + tempList[i].getName() + "\">" + tempList[i].getName() + "</a></p>");

            } else {
                stringBuilder.append("<p><a href=\"../main/index?path=" + pathName + "%2f" + tempList[i].getName() + "\">" + tempList[i].getName() + "</a></p>");
            }
        }
        stringBuilder.append(ResPath.Html_End);
        return stringBuilder.toString();
    }


    @RequestMapping(value = "/delete/{name}"
            , method = {RequestMethod.GET, RequestMethod.POST})
    public String deleteFile(@PathVariable String name) {
        String path = ResPath.DownloadPath;
        File file = new File(path + "/" + name);
        if (!file.exists()) {
            return name + "文件不存在";
        }
        if (file.isFile()) {
            if (file.delete()) {
                return name + "删除成功";
            } else {
                return name + "删除失败";
            }
        } else {
            return "不可以删除文件夹";
        }


    }

    @RequestMapping(value = "/getAllFile"
            , method = {RequestMethod.GET, RequestMethod.POST})
    public String getAllFile(@RequestParam(value = "path", required = false) String path) {
        List<FileBean> files = new ArrayList<FileBean>();
        File file = null;
        if (path != null && path.length() > 0) {
            file = new File(ResPath.DownloadPath + path);
        } else {
            file = new File(ResPath.DownloadPath);
            path = "";
        }
        File[] tempList = file.listFiles();

        for (int i = 0; i < tempList.length; i++) {
            if (tempList[i].isFile()) {
                files.add(new FileBean(path + "/" + tempList[i].getName(), tempList[i].length(), false));
            } else {
                files.add(new FileBean(path + "/" + tempList[i].getName(), tempList[i].length(), true));
            }
        }
        Gson gson = new Gson();
        return gson.toJson(files);
    }


    @RequestMapping(value = "/writeText"
            , method = {RequestMethod.GET, RequestMethod.POST})
    public String WriteText(@RequestParam("txt") String txt) {
        String path = ResPath.DownloadPath;
        File file = new File(path + "/" + "test.txt");

        FileOutputStream fileOutputStream = null;
        try {
            if (file.exists()) {
                //判断文件是否存在，如果不存在就新建一个txt
                file.createNewFile();
            }
            fileOutputStream = new FileOutputStream(file);
            fileOutputStream.write(txt.getBytes());
            fileOutputStream.flush();
            fileOutputStream.close();
            return "成功";
        } catch (Exception e) {
            e.printStackTrace();
            return "失败";
        }
    }

    @RequestMapping(value = "/readText"
            , method = {RequestMethod.GET, RequestMethod.POST})
    public String readText() {
        String path = ResPath.DownloadPath;
        File file = new File(path + "/" + "test.txt");
        if (file.isFile() && file.exists()) {
            try {
                FileInputStream fileInputStream = new FileInputStream(file);
                InputStreamReader inputStreamReader = new InputStreamReader(fileInputStream);
                BufferedReader bufferedReader = new BufferedReader(inputStreamReader);

                StringBuffer sb = new StringBuffer();
                String text = null;
                while ((text = bufferedReader.readLine()) != null) {
                    sb.append(text);
                    sb.append("\n");
                }
                sb.deleteCharAt(sb.length() - 1);
                return sb.toString();
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        return "没有数据";
    }
}
